import { forwardRef, useImperativeHandle, useEffect } from 'react';
import { Input } from 'antd';
import { inbiz } from '@inbiz/render';
import { Field } from '@formily/core';
import { connect, useField, mapProps } from '@formily/react';
import { getMessage, TextWidget } from '@inbiz/react';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from './api';
import './style.less';
const { TextArea } = Input;
type IProps = {
  value: string;
  readOnly: boolean;
  disabled: boolean;
  inbiz: inbiz;
  title: string;
  onChange: (value: string) => void;
  viewMode?:string;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  emit?: () => void;
} & typeof defaultProps;
const iconNoEnterReg =
  /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;

const EformTextArea = forwardRef((props: IProps, ref) => {
  const { callBackEvents, inbiz, maxLength, minLength, emit, title, placeholder,viewMode, ...other } = props;
  const [configEvents] = useEvents(props.callBackEvents, props.emit);

  // 自定义验证逻辑
  const filed = useField<Field>();

  useEffect(() => {
    filed.setValidatorRule('validator', (value: string, rule: any, ctx: any) => {
      if (maxLength && value) {
        if (maxLength && value?.length > maxLength) {
          return (
            <>
              <TextWidget>EformTextArea.validate.maxLengthNumber</TextWidget>
              {maxLength}
            </>
          );
        }
      }
      return true;
    });
  }, [maxLength]);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props, filed),
    }),
    [],
  );
  return (
    <>
   {viewMode=='look'?props?.value:
         <TextArea
         {...other}
         className="areaContent"
         maxLength={maxLength}
         placeholder={getMessage(placeholder)}
         disabled={props.readOnly || props.disabled}
         onChange={(e) => {
           props?.onChange?.((e.target.value || '').replace(iconNoEnterReg, ''));
         }}
       />
     }
   </>
  );
});

(
  EformTextArea as typeof EformTextArea & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props: any): string | void => {
  if (props.defaultValue && props.defaultValue.length > 0) {
    return props.defaultValue;
  }
};

EformTextArea.displayName = 'EformTextArea';

export default connect(
  EformTextArea,
  mapProps((props: IProps) => {
    const others = props;
    others.placeholder = getMessage(props.placeholder);
    return { ...others };
  }),
);
export type { IProps };
